# -*- coding:utf-8 -*-

from flask import request,g,jsonify,current_app,session
from ihome.models import Area,Facility,User,House,HouseImage,Order
from . import api
from ihome.utils.response_code import RET
from ihome import redis_store,db
from ihome.constants import AREA_INFO_REDIS_EXPIRES,QINIU_DOMIN_PREFIX,HOUSE_DETAIL_REDIS_EXPIRE_SECOND,HOME_PAGE_MAX_HOUSES,HOME_PAGE_DATA_REDIS_EXPIRES
from ihome.constants import HOUSE_LIST_PAGE_CAPACITY,HOUSE_LIST_REDIS_EXPIRES
from ihome.utils.common import login_required
from ihome.utils.storage_image import storage_image
import datetime

@api.route("/areas")
def get_areas():
    try:
        areas_array = redis_store.get("areas")
        if areas_array:
            return jsonify(errno = RET.OK,errmsg = "ok",data={"areas":eval(areas_array)})
    except Exception as e:
        current_app.logger.error(e)

    areas = Area.query.all()
    areas_array = []
    for area in areas:
        areas_array.append(area.to_dict())

    try:
        redis_store.set("areas",areas_array,AREA_INFO_REDIS_EXPIRES)
    except Exception as e:
        current_app.logger.error(e)

    return jsonify(errno = RET.OK,errmsg = "ok",data={"areas":areas_array})

@api.route("/house",methods = ["POST"])
@login_required
def save_new_house():
    user_id = g.user_id
    json_dict = request.json
    title = json_dict.get('title')
    price = json_dict.get('price')
    address = json_dict.get('address')
    area_id = json_dict.get('area_id')
    room_count = json_dict.get('room_count')
    acreage = json_dict.get('acreage')
    unit = json_dict.get('unit')
    capacity = json_dict.get('capacity')
    beds = json_dict.get('beds')
    deposit = json_dict.get('deposit')
    min_days = json_dict.get('min_days')
    max_days = json_dict.get('max_days')

    if not all(
            [title, price, address, area_id, room_count, acreage, unit, capacity, beds, deposit, min_days, max_days]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数缺失')

    try:
        price = int(float(price)*100)
        deposit = int(float(price)*100)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg = '请输入正确的价格')

    house = House()

    house.user_id = user_id
    house.area_id = area_id
    house.title = title
    house.price = price
    house.address = address
    house.room_count = room_count
    house.acreage = acreage
    house.unit = unit
    house.capacity = capacity
    house.beds = beds
    house.deposit = deposit
    house.min_days = min_days
    house.max_days = max_days

    facilities = json_dict.get('facility')
    if facilities:
        house.facilities = Facility.query.filter(Facility.id.in_(facilities)).all()

    try:
        db.session.add(house)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="添加数据失败")

    return jsonify(errno=RET.OK, errmsg="ok", data={"house_id": house.id})

@api.route("/house/<int:house_id>/images",methods=["POST"])
@login_required
def upload_house_image(house_id):
    try:
        house_image_file = request.files.get("house_image").read()

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')

    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.looger.error()
        return jsonify(errno=RET.DBERR, errmsg='查询信息失败')

    if not house:
        return jsonify(errno=RET.NODATA, errmsg='房屋不存在')

    try:
        url = storage_image(house_image_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='上传失败')

    house_image = HouseImage()
    house_image.house_id = house.id
    house_image.url = url

    try:
        if not house.index_image_url:
            house.index_image_url = url

        db.session.add(house_image)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='保存信息失败')

    return jsonify(errno=RET.OK, errmsg="OK", data={"url": QINIU_DOMIN_PREFIX + url})


@api.route("/house/<int:houst_id>")
def get_house_detail(houst_id):
    user_id = session.get("user_id")
    # print user_id
    # try:
    #     house_dict = redis_store.get("house_deatil_%d"%houst_id)
    #     if house_dict:
    #         return jsonify(errno=RET.OK, errmsg="OK", data={"user_id": user_id, "house": eval(house_dict)})
    # except Exception as e:
    #     current_app.logger.error(e)

    try:
        house = House.query.get(houst_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据库查询失败")

    if not house:
        return jsonify(errno=RET.NODATA, errmsg="房屋不存在")

    house_dict = house.to_full_dict()
    # try:
    #     redis_store.set(("house_deatil_%d"%houst_id),house_dict,HOUSE_DETAIL_REDIS_EXPIRE_SECOND)
    # except Exception as e:
    #     current_app.logger.error(e)

    return jsonify(errno=RET.OK, errmsg="OK", data={"user_id": user_id, "house": house_dict})


@api.route("/house/index")
def get_house_index():
    try:
        houses_dict = redis_store.get('home_house_index')
        if houses_dict:
            return jsonify(errno=RET.OK, errmsg="ok", data=eval(houses_dict))
    except Exception as e:
        current_app.logger.error(e)

    try:
        houses = House.query.order_by(House.order_count.desc()).limit(HOME_PAGE_MAX_HOUSES)

    except Exception as e:
        current_app.logger.error(e)
        return  jsonify(errno=RET.DBERR,errmsg="查询失败")

    houses_dict = []
    if houses:
        for house in houses:
            houses_dict.append(house.to_basic_dict())

        try:
            redis_store.set("home_house_index", houses_dict, HOME_PAGE_DATA_REDIS_EXPIRES)
        except Exception as e:
            current_app.logger.error(e)

        return jsonify(errno=RET.OK, errmsg="OK", data=houses_dict)

    # return jsonify(errno=RET.OK, errmsg="OK", data=houses_dict)


@api.route('/houses')
def sraech_house():

    args = request.args
    aid = args.get("aid",'')
    sd = args.get("sd",'')
    ed = args.get("ed",'')
    sk = args.get("sk","new")
    p = args.get("p",1)

    start_date = None
    end_date = None
    try:
        if sd:
            print type(sd)
            start_date = datetime.datetime.strptime(sd,"%Y-%m-%d")
        if ed:
            end_date = datetime.datetime.strptime(ed,"%Y-%m-%d")
        if end_date and start_date:
            assert start_date < end_date ,Exception("开始日期不能大于结束日期")
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.PARAMERR,errmsg = "参数有误")

    try:
        p = int(p)
    except Exception as e:
        return jsonify(enrrno = RET.PARAMERR,errmsg = "参数错误")

    # try:
    #     redis_key = "house_list_%s_%s_%s_%s"%(aid,sd,ed,sk)
    #     response_dict = redis_store.hget(redis_key,p)
    #     if response_dict:
    #         return jsonify(errno=RET.OK, errmsg='ok', data=eval(response_dict))
    # except Exception as e:
    #     current_app.logger.error(e)


    try:
        houses_query = House.query
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '查询失败')

    filters= []
    if aid:
        filters.append(House.area_id == aid)

    conflict_order = None
    if start_date and end_date:
        conflict_order = Order.query.filter(Order.begin_date < end_date, Order.end_date >start_date).all()
    if start_date:
        conflict_order = Order.query.filter(Order.end_date > start_date).all()
    if end_date:
        conflict_order = Order.query.filter(Order.begin_date < end_date).all()

    if conflict_order:
        conflict_house_ids = [order.house_id for order in conflict_order]
        filters.append(House.id.notin_(conflict_house_ids))

    if sk == "booking":
        houses_query = houses_query.filter(*filters).order_by(House.order_count.desc())
    elif sk == 'price-inc':
        houses_query = houses_query.filter(*filters).order_by(House.price)
    elif sk == 'price-dec':
        houses_query = houses_query.filter(*filters).order_by(House.price.desc())
    else:
        houses_query = houses_query.filter(*filters).order_by(House.create_time.desc())



    paginate = houses_query.paginate(p,HOUSE_LIST_PAGE_CAPACITY,False)
    houses = paginate.items
    total_page = paginate.pages

    # houses = houses_query.all()

    houses_dict = []
    for house in houses:
        houses_dict.append(house.to_basic_dict())

    response_dict = {"houses":houses_dict,'total_page':total_page}

    # if p <= total_page:
    #     try:
    #         redis_key = "house_list_%s_%s_%s_%s"%(aid,sd,ed,sk)
    #         # 创建事物对象
    #         pipe = redis_store.pipeline()
    #         pipe.multi()
    #         pipe.hset(redis_key,p,response_dict)
    #         pipe.expire(redis_key,HOUSE_LIST_REDIS_EXPIRES)
    #         pipe.execute()
    #     except Exception as e:
    #         current_app.logger.error(e)

    return jsonify(errno = RET.OK,errmsg = 'ok',data=response_dict)

